package cn.zhoabab.study.seata.order.service.impl;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import io.seata.spring.annotation.GlobalTransactional;

import cn.zhoabab.study.seata.order.dao.OrderMapper;
import cn.zhoabab.study.seata.order.entity.OrderEntity;
import cn.zhoabab.study.seata.order.entity.dto.OrderDTO;
import cn.zhoabab.study.seata.order.service.OrderService;
import cn.zhoabab.study.seata.storage.client.StorageFeignApi;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StorageFeignApi storageFeignApi;

    @Override
    @GlobalTransactional
    public Map<String, Object> purchase(OrderDTO orderDTO) {
        Map<String,Object> resultMap = new HashMap<>();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setId(orderDTO.getId());
        orderEntity.setAddress(orderDTO.getAddress());
        orderEntity.setCreateTime(new Date());
        orderEntity.setTotalPrice(orderDTO.getTotalPrice());
        orderEntity.setOrderNum(orderDTO.getOrderNum());
        // 本地事务
        int result = orderMapper.insert(orderEntity);
        log.info(">>>> insert result = {} <<<<",result);

        // 分支事务
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ResponseEntity response = storageFeignApi.reduceStock(orderDTO.getWarehouseCode(), orderDTO.getNums());
        log.info(">>>> warehouse response={}",response);

        resultMap.put("success",true);
        return resultMap;
    }

    @Override
    @GlobalTransactional
    public void update(OrderEntity orderEntity) {
        orderMapper.updateById(orderEntity);
    }
}
